<template>
  <div class="test-page">
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <span>前后端连接测试</span>
        </div>
      </template>
      
      <div class="test-content">
        <el-space direction="vertical" size="large" style="width: 100%">
          <!-- 连接状态 -->
          <el-alert
            :title="connectionStatus.title"
            :type="connectionStatus.type"
            :description="connectionStatus.description"
            show-icon
          />
          
          <!-- 测试按钮 -->
          <div class="test-buttons">
            <el-button 
              type="primary" 
              :loading="testing"
              @click="testConnection"
            >
              <el-icon><Connection /></el-icon>
              测试连接
            </el-button>
            
            <el-button 
              type="success" 
              :loading="initingUser"
              @click="testInitUser"
            >
              <el-icon><UserFilled /></el-icon>
              初始化测试用户
            </el-button>
            
            <el-button 
              type="warning" 
              :loading="testingLogin"
              @click="testLogin"
            >
              <el-icon><Key /></el-icon>
              测试登录
            </el-button>
          </div>
          
          <!-- 测试结果 -->
          <div v-if="testResults.length > 0" class="test-results">
            <h4>测试结果：</h4>
            <el-timeline>
              <el-timeline-item
                v-for="(result, index) in testResults"
                :key="index"
                :type="result.type"
                :timestamp="result.timestamp"
              >
                <div class="result-content">
                  <strong>{{ result.title }}</strong>
                  <p>{{ result.message }}</p>
                  <pre v-if="result.data" class="result-data">{{ result.data }}</pre>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-space>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Connection, UserFilled, Key } from '@element-plus/icons-vue'
import userApi from '@/api/user'
import axios from 'axios'

// 响应式数据
const testing = ref(false)
const initingUser = ref(false)
const testingLogin = ref(false)
const testResults = ref([])

// 连接状态
const connectionStatus = reactive({
  title: '未测试',
  type: 'info',
  description: '点击"测试连接"按钮检查前后端连接状态'
})

// 添加测试结果
const addResult = (title, message, type = 'primary', data = null) => {
  testResults.value.unshift({
    title,
    message,
    type,
    data: data ? JSON.stringify(data, null, 2) : null,
    timestamp: new Date().toLocaleString()
  })
}

// 测试基本连接
const testConnection = async () => {
  testing.value = true
  
  try {
    // 测试直接连接后端
    const response = await axios.get('http://localhost:5001/user/initTestUser', {
      timeout: 5000
    })
    
    connectionStatus.title = '连接成功'
    connectionStatus.type = 'success'
    connectionStatus.description = '前后端连接正常，可以正常通信'
    
    addResult('直接连接测试', '成功连接到后端服务', 'success', response.data)
    ElMessage.success('后端连接测试成功')
    
  } catch (error) {
    console.error('连接测试失败:', error)
    
    if (error.code === 'ECONNABORTED') {
      connectionStatus.title = '连接超时'
      connectionStatus.type = 'error'
      connectionStatus.description = '连接后端服务超时，请检查后端服务是否启动'
    } else if (error.message.includes('Network Error')) {
      connectionStatus.title = '网络错误'
      connectionStatus.type = 'error'
      connectionStatus.description = '无法连接到后端服务，请检查后端是否在 localhost:5001 运行'
    } else {
      connectionStatus.title = '连接失败'
      connectionStatus.type = 'error'
      connectionStatus.description = `连接错误: ${error.message}`
    }
    
    addResult('直接连接测试', `连接失败: ${error.message}`, 'danger')
    ElMessage.error('后端连接测试失败')
  } finally {
    testing.value = false
  }
}

// 测试初始化用户
const testInitUser = async () => {
  initingUser.value = true
  
  try {
    const result = await userApi.initTestUser()
    addResult('初始化测试用户', '成功初始化测试用户', 'success', result)
    ElMessage.success('测试用户初始化成功')
  } catch (error) {
    console.error('初始化用户失败:', error)
    addResult('初始化测试用户', `初始化失败: ${error.message}`, 'danger')
    ElMessage.error('测试用户初始化失败')
  } finally {
    initingUser.value = false
  }
}

// 测试登录
const testLogin = async () => {
  testingLogin.value = true
  
  try {
    const result = await userApi.login({
      username: 'admin',
      password: 'admin123'
    })
    addResult('测试登录', '登录测试成功', 'success', result)
    ElMessage.success('登录测试成功')
  } catch (error) {
    console.error('登录测试失败:', error)
    addResult('测试登录', `登录失败: ${error.message}`, 'danger')
    ElMessage.error('登录测试失败')
  } finally {
    testingLogin.value = false
  }
}
</script>

<style scoped>
.test-page {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.test-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.test-content {
  padding: 20px 0;
}

.test-buttons {
  display: flex;
  gap: 16px;
  justify-content: center;
  flex-wrap: wrap;
}

.test-results {
  margin-top: 30px;
}

.test-results h4 {
  margin: 0 0 16px 0;
  color: #303133;
}

.result-content {
  padding: 8px 0;
}

.result-content strong {
  color: #303133;
  font-size: 16px;
}

.result-content p {
  margin: 4px 0;
  color: #606266;
}

.result-data {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.4;
  margin-top: 8px;
  max-height: 200px;
  overflow-y: auto;
  border-left: 4px solid #409eff;
}
</style>
